package com.example.aitoedu.controller.teacher;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.aitoedu.dto.PlDTO;
import com.example.aitoedu.dto.PwdChangeDTO;
import com.example.aitoedu.entity.Teacher;
import com.example.aitoedu.service.TeacherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/teacher")
@Slf4j
@CrossOrigin
@Tag(name = "教师端相关接口")
@SaCheckRole("教师")
public class TeacherController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/pl")
    @Operation(summary = "个人信息")
    public SaResult pl(){
        Long id = Long.valueOf(StpUtil.getLoginId().toString());
        Teacher teacher = (Teacher) redisTemplate.opsForValue().get("teacher_pl:"+id);
        if(teacher != null) return SaResult.ok().setData(teacher);
        teacher = teacherService.pl();
        redisTemplate.opsForValue().set("teacher_pl:"+id,teacher);
        return SaResult.ok().setData(teacher);
    }

    @PostMapping("/update/picture")
    @Operation(summary = "修改头像")
    public SaResult update_picture(MultipartFile file){
        this.delete_pl();
        teacherService.update_picture(file);
        return SaResult.ok("修改头像成功");
    }
    @PostMapping("/update/pwd")
    @Operation(summary = "修改密码")
    public SaResult update_pwd(@RequestBody PwdChangeDTO pwdChangeDTO){
        System.out.println(pwdChangeDTO);;
        this.delete_pl();
        return teacherService.update_pwd(pwdChangeDTO);
    }
    @PostMapping("/update/pl")
    @Operation(summary = "修改个人信息")
    public SaResult update_pl(@RequestBody PlDTO plDTO){
        this.delete_pl();
        return teacherService.update_pl(plDTO);
    }
    private void delete_pl(){
        Long id = Long.valueOf(StpUtil.getLoginId().toString());
        redisTemplate.delete("teacher_pl:"+id);
    }
}
